﻿using MediatR;
using S.Common.ApiResult;
using S.PurchaseAndSales.Domain.Model;
using S.PurchaseAndSales.Infrastructure.Interface.SalesForm;
using S.PurchaseAndSales.Read.Api.Application.Command.SheepSaleCommand;

namespace S.PurchaseAndSales.Read.Api.Application.CommandHandlers.SheepSaleHandler
{
    public class GetCustomerListHandler : IRequestHandler<GetCustomerListCommand, ApiResult<List<CustomerInformationModel>>>
    {

        private readonly ICustomerRepository customer;

        public GetCustomerListHandler(ICustomerRepository customer)
        {
            this.customer = customer;
        }

        public async Task<ApiResult<List<CustomerInformationModel>>> Handle(GetCustomerListCommand request, CancellationToken cancellationToken)
        {
            //获取到所有数据
            var  list = await customer.GetAllAsync();

            //条件查询
            if (request.CustomerInformationId != 0)
            {
                list=list.Where(m=>m.CustomerInformationId == request.CustomerInformationId).ToList();
            }
            if (!string.IsNullOrEmpty(request.customerName))
            {
                list=list.Where(m=>m.CustomerName.Contains(request.customerName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ChargePersonPhone))
            {
                list=list.Where(m=>m.ChargePersonPhone.Contains(request.ChargePersonPhone)).ToList();
            }
            if (!string.IsNullOrEmpty(request.Market))
            {
                list=list.Where(m=>m.Market.Contains(request.Market)).ToList();
            }
            if (!string.IsNullOrEmpty(request.salesman))
            {
                list=list.Where(m=>m.Salesman.Contains(request.salesman)).ToList();
            }
            if (!string.IsNullOrEmpty(request.CollectionFile))
            {
                list=list.Where(m=>m.CollectionFile.Contains(request.CollectionFile)).ToList();
            }
            if (!string.IsNullOrEmpty(request.CustomLabel))
            {
                list=list.Where(m=>m.CustomLabel.Contains(request.CustomLabel)).ToList();
            }
            if (request.UseCondition != 0)
            {
                list=list.Where(m=>m.UseCondition==request.UseCondition).ToList();
            }
            ApiResult<List<CustomerInformationModel>> result = new ApiResult<List<CustomerInformationModel>>();

            //总页数、总条数
            int totalCount = list.Count;
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            result.totalCount = totalCount;
            result.pageCount = pageCount;
            // 对列表进行分页处理
            result.Data = list.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            return result;
        }
    }
}
